﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using erpIngesup.Models;

namespace erpIngesup.Controllers
{
    public class logController : Controller
    {
        private erpInsiaEntities db = new erpInsiaEntities();
        //
        // GET: /log/

        [AllowAnonymous]
        public ActionResult Connexion()
        {
            if (Request.IsAuthenticated)
            {
                return View("Forbidden");
            }
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Connexion(PersonneView personne)
        {
            if (ModelState.IsValid)
            {
                //personne.MDP = Security.getHash(personne.MDP);
                if (Membership.ValidateUser(personne.LOGIN, personne.MDP))
                {
                    FormsAuthentication.SetAuthCookie(personne.LOGIN, true);
                    string role = db.PersonneView.SingleOrDefault(pers => pers.LOGIN == personne.LOGIN && pers.MDP == personne.MDP).ROLE;
                    bool rep = Roles.IsUserInRole(role);
                    if (rep)
                    {
                        Roles.AddUserToRole(personne.LOGIN, role);
                    }
                    Session["login"] = personne.LOGIN;
                    return RedirectToAction("index", "home", new { area = role });
                }
                else
                {
                    ViewData["error"] = "Erreur d'identification";
                }
            }
            return View();
        }

        [Authorize]
        public ActionResult Deconnexion()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "home");
        }
    }
}
